﻿using CommonUtils.APIWrapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonUtils
{
    public class IniReader
    {
        public static string GetProfileString(string section, string key, string defaultValue, string filePath)
        {
            StringBuilder temp = new StringBuilder(256);
            int i = Kernel32API.GetPrivateProfileString(section, key, defaultValue, temp, 256, filePath);
            if (i >= 256)
            {
                temp = new StringBuilder(i + 1);
                i = Kernel32API.GetPrivateProfileString(section, key, defaultValue, temp, i + 1, filePath);
            }

            return i > 0 ? temp.ToString() : null;
        }

        public static bool GetProfileBool(string section, string key, bool defaultValue, string filePath)
        {
            try
            {
                return Convert.ToBoolean(IniReader.GetProfileString(section, key, Convert.ToString(defaultValue), filePath));
            }
            catch (Exception ex)
            {
                new Log(typeof(IniReader).ToString()).E(ex);

                return defaultValue;
            }
        }

        public static Int32 GetProfileInt(string section, string key, Int32 defaultValue, string filePath)
        {
            try
            {
                string value = IniReader.GetProfileString(section, key, Convert.ToString(defaultValue), filePath);
                return Int32.Parse(value);
            }
            catch (Exception ex)
            {
                new Log(typeof(IniReader).ToString()).E(ex);

                return defaultValue;
            }
        }
    }
}
